﻿using MapHello.Basic;
using MapHello.Data;
using System;
using System.Collections.Generic;
using System.Device.Location;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace MapHello
{
    public class PositionGeoCoordinateConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Position obj = value as Position;
            //double zoomLevel = (double)parameter;
            if (obj.Latitude.HasValue && obj.Longitude.HasValue)
            {
                double latitude = obj.Latitude.Value;
                double longitude = obj.Longitude.Value;

                //Utility.OffsetMapLocation(ref latitude, ref longitude, zoomLevel);

                return new GeoCoordinate(latitude, longitude);
            }
            else
            {
                return new GeoCoordinate(0, 0);
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            GeoCoordinate obj = value as GeoCoordinate;
            return new Position() { Latitude = obj.Latitude, Longitude = obj.Longitude, ModifiedOn = DateTime.Now };
        }
    }

    public class PersonImageBinaryToImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            byte[] imageBinary = value as byte[];
            BitmapImage img = new BitmapImage();
            using (MemoryStream stream = new MemoryStream(imageBinary))
            {
                try
                {
                    img.SetSource(stream);
                }
                catch (Exception e)
                {
                    // clear fault stream
                    // TODO: set default image
                }
            }
            return img;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }

    public class BoolToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return ((bool)value) ? Visibility.Visible : Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Visibility.Visible == ((Visibility)value) ? true : false;
        }
    }
}
